/**
 * 
 */
package com.audi.box.server.handler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.audi.box.controller.IController;
import com.google.gson.Gson;

/**
 * @author HuyPVA
 * 
 */
public abstract class Handler implements IHandler {
	private IController controller;
	private Gson gson;

	public Handler(IController controller) {
		this.controller = controller;
		gson = new Gson();
	}

	protected IController getController() {
		return controller;
	}

	public Gson getGson() {
		return gson;
	}

	public <T> List<T> convertJson2List(String data, Class<T> tClass) {
		Type type = new ListParameterizedType(tClass);
        List<T> list = gson.fromJson(data, type);
        return list;
	}

	/**
	 * Convert data json to object 
	 * @param data
	 * @param classOfT
	 * @return
	 */
	public <T> T convertJson2Obj(String data, Class<T> classOfT) {
		return gson.fromJson(data, classOfT);
	}

	private class ListParameterizedType implements ParameterizedType {

		private Type type;

		private ListParameterizedType(Type type) {
			this.type = type;
		}

		@Override
		public Type[] getActualTypeArguments() {
			return new Type[] { type };
		}

		@Override
		public Type getRawType() {
			return ArrayList.class;
		}

		@Override
		public Type getOwnerType() {
			return null;
		}
	}
}
